package com.gaoxinfu.demo.spring.cloud.jpa.customize.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gaoxinfu.demo.spring.cloud.jpa.customize.annotation.JpaColumn;
import com.gaoxinfu.demo.spring.cloud.jpa.customize.annotation.JpaOperator;
import com.gaoxinfu.demo.spring.cloud.jpa.customize.constant.JpaOperatorConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

/**
 * jpa自动拼接SQL相关运算符工具类
 * @author  gaoxinfu
 */
@Slf4j
public class JpaOperatorUtil {

    /**
     *
     * @param obj  入参对象
     * @param querySql   固定SQL
     * @return
     */
    public static String addConditionSql(Object obj, StringBuilder querySql){
        if (StringUtils.isEmpty(querySql)){
            throw new RuntimeException("querySql 不能为空");
        }
        Map map =  JSONObject.parseObject(JSON.toJSONString(obj), Map.class);
        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        Field[] fields = obj.getClass().getFields();
        while(iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            if (StringUtils.isEmpty(entry.getValue())){
                continue;
            }
            if (entry.getKey().equals("pageNo")||entry.getKey().equals("pageSize")){
                continue;
            }
            for (Field field:fields){
                if (entry.getKey().equals(field.getName())){
                    String operator = JpaOperatorConstant.EQUALS;
                    JpaOperator jpaOperator = field.getAnnotation(JpaOperator.class);
                    if (jpaOperator != null && !StringUtils.isEmpty(jpaOperator.value())){
                        operator = jpaOperator.value();
                    }
                    //默认对象字段和表字段一致
                    String tableField = entry.getKey();
                    JpaColumn jpaColumn = field.getAnnotation(JpaColumn.class);
                    if (jpaColumn != null && !StringUtils.isEmpty(jpaColumn.value())){
                        tableField = jpaColumn.value();
                    }
                    querySql.append("and "+tableField +operator+"'"+entry.getValue()+"'");
                }
            }
        }
        return querySql.toString();
    }
}
